const express = require('express')
const superagent = require('superagent')
const cheerio = require('cheerio')
var router = express.Router();
let mvname
let mvhtml = []
let mvs = []
var getMovie1 = (res) => {
    let mvss = {}
    let $ = cheerio.load(res.text)
        // console.log($);
    let obj = {}
    let list = []
        //获取script部分
    let url;
    let hrefs = $('.player').find('script').html()
    hrefs = unescape(hrefs)
    hrefs = hrefs.split("unescape('")
    hrefs = hrefs[1]
        //url处理
    let rootarr = hrefs.split('$$$')

    for (const idx in rootarr) {
        rootarr[idx] = rootarr[idx].replace("');", '')
        rootarr[idx] = rootarr[idx].split('#')
        for (let key in rootarr[idx]) {

            rootarr[idx][key] = rootarr[idx][key].split('$')
            let i = rootarr[idx][key][1].indexOf('m3u8')
            if (i !== -1) {
                rootarr[idx][key][1] = 'http://www.dplayer.tv/dp/?url=' + rootarr[idx][key][1]
                    // console.log(rootarr[idx][key][1]);
            }
        };
    }
    // 处理视频网址
    // console.log(rootarr);
    return rootarr
}
router.get('/', function(req, res) {
    let ip = req.headers['x-real-ip'] ? req.headers['x-real-ip'] : req.ip.replace(/::ffff:/, '')
    console.log(ip);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    mvid = req.query.id
    console.log(mvid);
    var http = encodeURI(`http://kk2w.cc/?m=vod-play-id-${mvid}-src-1-num-1.html`)
    superagent.get(http, function(err, resulst) {
        let mvhtml = []
        let msg = ''
        try {
            if (!err) {
                msg = 'ok'
                mvhtml = getMovie1(resulst);
            }
        } catch (error) {
            console.log(error);
        }
        let data = {
            msg: 'ok',
            data: mvhtml,
        }
        try {
            res.send(data)
        } catch (error) {
            res.send('fail')
        }
    })
})
module.exports = router